import axios, {type AxiosInstance} from "axios";
import {UserApi} from "./UserApi.ts";
import {TopicApi} from "./TopicApi.ts";
import {ForumApi} from "./ForumApi.ts";
import {ElMessage} from "element-plus";
import {ItemApi} from "./ItemApi.ts";
import {TopicReadApi} from "./TopicReadApi.ts";
import {PostApi} from "./PostApi.ts";
import {parseLocation} from "../types/NgaLocation.ts";
import {MessageApi} from "./MessageApi.ts";
import {NoticeApi} from "./NoticeApi.ts";
import {FavorApi} from "./FavorApi.ts";

export class NgaApi {
    readonly instance: AxiosInstance;
    readonly user: UserApi;
    readonly topic: TopicApi;
    readonly forum: ForumApi;
    readonly item: ItemApi;
    readonly read: TopicReadApi;
    readonly post: PostApi;
    readonly message: MessageApi;
    readonly notice: NoticeApi;
    readonly favor: FavorApi;

    constructor(baseUrl: string) {
        this.instance = axios.create({
            baseURL: baseUrl,
            timeout: 20000,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        });
        // 响应拦截器
        this.instance.interceptors.response.use(response => {
            const json = response.data

            formatError(json)
            // 自动拆包
            if (json.data && response.config.url === 'nuke.php') {
                const keys = Object.keys(json.data);
                if (keys.length === 1) {
                    json.data = json.data[keys[0]]
                }
            }

            if (response.data.error && !response.data.data) {
                const res = response.data
                console.warn('请求异常', res)
                return Promise.reject(res)
            }
            // console.log(response)
            return response
        }, error => {
            const response = error.response
            const json = response.data
            formatError(json)
            const message = (json && json.error) ? `${json.error.code}:${json.error.message}` : response.message
            ElMessage.error(`[${response.status}] ${message}`)
            return Promise.reject(json)
        })
        // 请求拦截器
        this.instance.interceptors.request.use(config => {
            config.params = Object.assign({}, config.params, {__inchst: "UTF8"})
            // console.log(config)
            return config
        })

        this.user = new UserApi(this.instance)
        this.topic = new TopicApi(this.instance)
        this.forum = new ForumApi(this.instance)
        this.item = new ItemApi(this.instance)
        this.read = new TopicReadApi(this.instance)
        this.post = new PostApi(this.instance)
        this.message = new MessageApi(this.instance)
        this.notice = new NoticeApi(this.instance)
        this.favor = new FavorApi(this.instance)
    }
}

const formatError = (json: any) => {
    // 规范化报错响应
    if (json.data && json.data.hasOwnProperty("__MESSAGE")) {
        const {'0': code, '1': message, '4': uri} = json.data["__MESSAGE"]
        if (code) {
            json.error = {code, message}
            delete json.data
        } else if (uri) {
            // 发帖跳转
            json.data = parseLocation(uri)
        }
    }
}
